<template>
	<div class="addBox">
		<div class="addBoxTop">
			<span class="font_size20"> 扫码下单 </span>
		</div>
		<div class="addDiv" v-loading="sLoading">
			<el-form ref="form" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择" :disabled="(isDisabled && !isEdit)">
						<el-option v-for="item in getYunShopsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="二维码样式" prop="ptype">
					<div class="pl-box flex_around" style="cursor: pointer;">
						<div class="flex_center_column flex_around mr20" v-for="option in layoutOptions"
							:key="option.value" @click="handleChangeTplOrsort(option.value)">
							<div style="height: 100px;" class="flex_center_column">
								<text class="font_bule" v-if="option.value == 1">{{ option.label }}</text>
								<text class="font_bule" v-if="option.value == 5">{{ option.label }}</text>
								<text class="font_bule" v-if="option.value == 6"
									style="position: relative;left: -20px;">{{ option.label
									}}</text>
								<el-image src="static/images/scan01.png" />
								<text class="font_bule" v-if="option.value == 2">{{ option.label }}</text>
								<text class="font_bule" v-if="option.value == 3"
									style="position: relative;left: -20px;">{{ option.label
									}}</text>
							</div>
							<div class="flex_row" style="margin-top: -5px;">
								<el-radio :disabled="(isDisabled && !isEdit)" v-model="objectForm.ptype"
									:label="option.value"></el-radio>
								<span :class="['ml5', { 'active-text': objectForm.ptype == option.value }]">
									{{ option.text }}
								</span>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="二维码类型" prop="isone">
					<div class="mb10">
						<el-radio-group v-model="objectForm.isone" :disabled="(isDisabled && !isEdit)" size="small"
							@change="changeIsone">
							<el-radio border :label="item.id" v-for="item in isoneTypeList">{{ item.name }}</el-radio>
						</el-radio-group>
					</div>
					<div class="pl-box">
						<div class="flex_row mb10 mt10" v-for="(item, index) in objectForm.qcode_ls">
							<div class="label-box flex_row flex1">
								<div class="flex_between flex1">
									<div class="flex_row">
										<div class="flex_row">
											<span class="mr5">二维码编号</span>
											<el-input style="width: 200px;" v-model="item.mecode"
												placeholder="内部使用编号(必填)" show-word-limit
												:disabled="(isDisabled && !isEdit)"></el-input>
										</div>
										<div class="flex_row ml30">
											<span class="mr5">二维码文字</span>
											<el-input style="width: 200px;" v-model="item.title" placeholder="客户可见文字"
												show-word-limit :disabled="(isDisabled && !isEdit)"></el-input>
										</div>
									</div>
									<div class="font_bule cursor_pointer" v-if="item.qrcode"
										@click="showQrcode(item)"> 查看二维码 </div>
								</div>
								<div class="object-item-delete-box" @click="deleteObject(index)"
									v-if="((isDisabled || isEdit) || objectForm.act == 'add') && (objectForm.isone == 2 && objectForm.qcode_ls.length > 1)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object ml20">
								<el-button type="primary"
									v-if="objectForm.qcode_ls.length - 1 == index && objectForm.isone == 2"
									@click="addObject" icon="el-icon-plus" circle
									:disabled="(isDisabled && !isEdit)"></el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="备注" prop="txt">
					<el-input type="textarea" v-model="objectForm.txt" class="input-w" placeholder="请填写备注"
						show-word-limit :disabled="(isDisabled && !isEdit)"></el-input>
				</el-form-item>
				<el-form-item label="启用" prop="value1">
					<div class="switchDiv">
						<el-switch v-model="objectForm.value1" :disabled="(isDisabled && !isEdit)"></el-switch>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="addDivBtn">
			<div class="acvite-btn" v-if="stopShow" @click="stopActivity">停止</div>
			<div class="acvite-btn" v-if="editShow" @click="editActivity">编辑</div>
			<div class="acvite-btn" v-if="btnShow" @click="createActivity">提交</div>
			<div class="back-btn" @click="goBack" v-if="isEdit || objectForm.act == 'add'">返回</div>
		</div>
		<ayjDialog title="二维码" width="40%" ref="qrcodeRef" top="5vh" :slotFooter="false" @closeFun="posterClose">
			<div class="qr-txt-box" style="width: 100%;min-height: 750px;position: relative;">
				<h4 class="p-txt"> 请截图分享二维码 </h4>
				<div v-if="objectForm.ptype == 5" class="text-top-center">
					<span>{{ currentQrInfo.title || '' }}</span>
				</div>
				<div v-if="objectForm.ptype == 6" class="text-top-left">
					<span>{{ currentQrInfo.title || '' }}</span>
				</div>
				<el-image v-if="qrcodeUrl" :src="qrcodeUrl" style="margin: 0 auto;" fit="fill" :style="{
					width: '600px',
					height: '600px',
				}" />
				<div v-if="objectForm.ptype == 2" class="text-bottom-center">
					<span>{{ currentQrInfo.title || ''  }}</span>
				</div>
				<div v-if="objectForm.ptype == 3" class="text-bottom-left">
					<span>{{ currentQrInfo.title || ''  }}</span>
				</div>
			</div>
		</ayjDialog>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, defineExpose } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { priceInput } from '@/utils/common.js'
import { isoneTypeList } from '@/utils/dict.js'

// 获取当前组件实例
const { proxy } = getCurrentInstance()
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => [],
	},
	detailID: {
		type: String,
		default: "",
	},
	box_index_key: {
		type: [String, Number],
		default: '',
	},
})

const emit = defineEmits(['addTpBmFun'])
const form = ref(null)
const sLoading = ref(false)
const isEdit = ref(false)
const layoutOptions = ref([])

const objectForm = ref({
	act: "add",
	id: "",
	shopid_yd: "",
	title: "", // 规则名称
	ptype: "", // 二维码样式
	isone: '1',
	txt: "", // 备注
	status: '', // 状态 1启用 2 停用
	value1: true, // 启用
	qcode_ls: [{
		mecode: "",
		title: ""
	}],
})

const editShow = computed(() => {
	return (objectForm.value.status == 2 && objectForm.value.act == 'add') || (objectForm.value.act == 'edt' && props.box_index_key == '1' && !isEdit.value)
})

const btnShow = computed(() => {
	return props.box_index_key == '2' || isEdit.value || objectForm.value.act == 'add'
})

const stopShow = computed(() => {
	return objectForm.value.status == 1 && !isEdit.value && objectForm.value.act != 'add'
})

const editActivity = () => {
	isEdit.value = true
}

const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	ptype: [
		{ required: true, message: '请选择二维码样式', trigger: 'blur' }
	],
})
const currentQrInfo = ref({})
const qrcodeRef = ref(null)
const qrcodeUrl = ref("")
const showQrcode = (data) => {
	currentQrInfo.value = data
	qrcodeRef.value.open()
	qrcodeUrl.value = data.qrcode
}

const posterClose = () => {
	qrcodeRef.value.close()
	qrcodeUrl.value = ""
}

const handleChangeTplOrsort = (val) => {
	if (isDisabled.value && !isEdit.value) {
		return
	}
	objectForm.value.ptype = val
}

const originalFormData = ref([])
const changeIsone = (val) => {
	objectForm.value.isone = val
	let chicData = [...originalFormData.value]
	if (chicData.length == 0) {
		chicData = [{
			mecode: "",
			title: ""
		}]
	}
	if (val == 1) {
		objectForm.value.qcode_ls = chicData.splice(0, 1)
	} else {
		objectForm.value.qcode_ls = chicData
	}
}

// 实现添加数组元素的方法
const addObject = () => {
	objectForm.value.qcode_ls.push({
		mecode: "",
		title: ""
	});
};

// 实现删除数组元素的方法
const deleteObject = (index) => {
	if (isDisabled.value && !isEdit.value) {
		return
	}
	if (objectForm.value.qcode_ls && objectForm.value.qcode_ls.length > 0) {
		// 确认删除
		proxy.$confirm('确定要删除这条数据吗?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			// 从数组中删除指定索引的元素
			objectForm.value.qcode_ls.splice(index, 1);
			proxy.$message.success('删除成功');
		}).catch(() => {
			// 取消删除
			proxy.$message.info('已取消删除');
		});
	}
};

const restFun = () => {
	objectForm.value.id = "";
	objectForm.value.act = 'add';
	objectForm.value.qcode_ls = [{
		mecode: "",
		title: ""
	}]
	originalFormData.value = [];
	detailsId.value = '';
	form.value?.resetFields();
}

const submitForm = async () => {
	console.log("objectForm.value=", objectForm.value)
	const valid = await form.value?.validate()
	if (valid) {
		const params = {
			...objectForm.value,
			status: objectForm.value.value1 ? 1 : 2,
		}
		const res = await proxy.$api({ url: config.yx_scan_order_save, data: params })
		if (res.status == 1) {
			proxy.$message.success(res?.msg || '操作成功')
			isEdit.value = false
			emit("addTpBmFun", {
				type: objectForm.value.act,
				status: objectForm.value.value1 ? 1 : 2,
			})
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	}
}

const createActivity = () => {
	submitForm("form")
}
const stopActivity = async () => {
	proxy.$confirm(`此操作将停止【${objectForm.value.title}】规则, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		let params = {
			...objectForm.value,
			isbase: objectForm.value.isbase.toString(),
			act: 'stop',
			status: 3,
		}
		let res = await proxy.$api({ url: config.yx_jf_event_save, data: params });
		if (res.status == 1) {
			proxy.$message({
				message: '停止成功',
				type: 'success'
			});
			emit("addTpBmFun", {
				type: 'del',
			})
		} else {
			proxy.$message({
				message: res?.msg || '停止失败',
				type: 'error'
			})
		}
	})
}

// 获取布局
const getLayout = async () => {
	await proxy.$api({ url: config.yx_scan_order_event_addinfo, data: {} }).then(res => {
		if (res.status == 1) {
			let result = res.data?.ptxt_ls
			layoutOptions.value = result.map(vm => {
				return {
					...vm,
					label: vm.title,
					value: vm.id,
					text: '扫我下单'
				}
			})
		}
	}).finally(() => { })
}
getLayout()

const goBack = () => {
	isEdit.value = false
	emit("backFun", 'back')
}

// 获取详情
const getDetail = async () => {
	sLoading.value = true
	const res = await proxy.$api({ url: config.yx_scan_order_info, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	if (res.status === 1 && res.data) {
		// 将获取到的数据赋值到 objectForm
		const data = res.data
		objectForm.value.id = data?.info?.id;
		objectForm.value = {
			...objectForm.value,
			...data.info,
			isone: data?.info?.isone,
			ptype: data?.info?.title_p,
			qcode_ls: data?.ls && data?.ls.length > 0 ? data?.ls?.map(vm => {
				return {
					...vm,
				}
			}) : [{
				mecode: "",
				title: ""
			}],
			act: 'edt',
			value1: data?.info?.status == 1 ? true : false,
		}
		console.log("objectForm.value=", objectForm.value)
		originalFormData.value = data?.ls && data?.ls.length > 0 ? data?.ls : [{
			mecode: "",
			title: ""
		}]
	}
}

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	console.log("newVal=xxxx", newVal)
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			form.value?.resetFields()
		}
		if (!newVal) {
			restFun()
		}
	}, 200)
}, { immediate: true })

onMounted(() => { })

// 添加计算属性
const isDisabled = computed(() => {
	const disabledStatus = ['1']
	return disabledStatus.includes(objectForm.value.status)
})

const getYunShopsList = computed(() => {
	return props.getYunShopList
})

defineExpose({
	restFun,
	objectForm
})


</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;

			span {
				margin-right: 20px;
			}
		}
	}
}

.pl-box {
	padding: 10px 20px;
	background-color: #f5f4f4;
	border-radius: 6px;
}

.label-box {
	position: relative;
	flex: 1;
	box-sizing: border-box;
	height: 80px;
	padding: 10px 30px 10px;
	border: 1px solid #DCDFE6;
	border-radius: 6px;
	gap: 10px;

	.object-item-delete-box {
		position: absolute;
		right: 0;
		top: 0;
		cursor: pointer;
		width: 20px;
		height: 20px;
		background-color: rgba(0, 0, 0, 0.1);
		border-bottom-left-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
		font-size: 12px;

		&:hover {
			background: rgba(0, 0, 0, 0.3);
		}
	}
}

.acvite-btn {
	opacity: 1;
	cursor: pointer;
}

::v-deep .el-icon-close:before {
	content: "\e6df";
}

::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
	background-color: #fcfcfc !important;
	color: #666 !important;
	border-color: #f1f1f1 !important;
}

.pl-box ::v-deep .el-radio {
	margin-right: 0 !important;
}

.pl-box ::v-deep .el-radio__label {
	display: none;
}

.qr-txt-box {
	position: relative;
	width: 100%;
	min-height: 750px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;

	.p-txt{
		position: absolute;
		top: 0px;
		z-index: 10;
	}

	// 顶部居中文字
	.text-top-center {
		position: absolute;
		top: calc(50% - 320px);
		left: 0;
		width: 100%;
		text-align: center;
		font-size: 18px;
		font-weight: 500;
		color: #333;
		z-index: 5;
	}

	// 顶部居左文字
	.text-top-left {
		position: absolute;
		top: calc(50% - 320px);
		left: 50%;
		transform: translateX(calc(-50% - 300px));
		font-size: 18px;
		font-weight: 500;
		color: #333;
		z-index: 5;
		white-space: nowrap;
	}

	// 底部居中文字
	.text-bottom-center {
		position: absolute;
		top: calc(50% + 320px);
		left: 0;
		width: 100%;
		text-align: center;
		font-size: 18px;
		font-weight: 500;
		color: #333;
		z-index: 5;
	}

	// 底部居左文字
	.text-bottom-left {
		position: absolute;
		top: calc(50% + 320px);
		left: 50%;
		transform: translateX(calc(-50% - 300px));
		font-size: 18px;
		font-weight: 500;
		color: #333;
		z-index: 5;
		white-space: nowrap;
	}
}
</style>